package com.quectel.core.module.invoice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.core.invoice.InvoiceConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.invoice.dao.InvoiceItemDao;
import com.quectel.core.module.invoice.dto.InvoiceItemDto;
import com.quectel.core.module.invoice.entity.InvoiceItemEntity;
import com.quectel.core.module.invoice.service.InvoiceItemService;
import com.quectel.core.module.parking.dto.ParkingOrderDto;
import com.quectel.core.module.parking.service.ParkingOrderService;
import com.quectel.core.module.parkingcard.dto.ParkingCardOrderDto;
import com.quectel.core.module.parkingcard.service.ParkingCardOrderService;
import com.quectel.core.module.propertybill.dto.PropertyBillDto;
import com.quectel.core.module.propertybill.service.PropertyBillService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/03/31 16:28
 */
@DubboService
public class InvoiceItemServiceImpl extends ServiceImpl<InvoiceItemDao, InvoiceItemEntity> implements InvoiceItemService {

    private static final Logger LOGGER = LoggerFactory.getLogger(InvoiceItemService.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> INVOICE_ITEM_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "INVOICE_ITEM_CACHE_BY_ID:%d", id);
    private static final Function<Long, String> INVOICE_ITEM_CACHE_BY_INVOICE_ID_FUNC = invoiceId -> String.format(RedisCacheConstants.PROJECT_NAME + "INVOICE_ITEM_CACHE_BY_INVOICE_ID_FUNC:%d", invoiceId);


    /**
     * 清除缓存方法
     */
    private static final Consumer<InvoiceItemDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(INVOICE_ITEM_CACHE_BY_ID_FUNC.apply(dto.getId()));
        CacheKit.invalidRedisCache(INVOICE_ITEM_CACHE_BY_INVOICE_ID_FUNC.apply(dto.getInvoiceId()));
    };

    @Autowired
    private InvoiceItemDao invoiceItemDao;
    @Autowired
    private PropertyBillService propertyBillService;
    @Autowired
    private ParkingCardOrderService parkingCardOrderService;
    @Autowired
    private ParkingOrderService parkingOrderService;


    @Override
    public void batchSave(List<InvoiceItemDto> invoiceItemDto) {
        List<InvoiceItemEntity> list = CopyUtils.copyList(invoiceItemDto, InvoiceItemEntity.class);
        list.forEach(commonInvoiceItem -> commonInvoiceItem.setId(Snowflake.nextId()));
        super.saveBatch(list);
    }

    @Override
    public void deleteByInvoiceId(Long invoiceId) {
        invoiceItemDao.delete(new LambdaQueryWrapper<InvoiceItemEntity>().eq(InvoiceItemEntity::getInvoiceId, invoiceId));
    }

    @Override
    public List<InvoiceItemDto> selectByInvoiceId(Long commonInvoiceId) {
        List<InvoiceItemEntity> list = invoiceItemDao.selectList(new LambdaQueryWrapper<InvoiceItemEntity>().eq(InvoiceItemEntity::getInvoiceId, commonInvoiceId));
        List<InvoiceItemDto> result = CopyUtils.copyList(list, InvoiceItemDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<InvoiceItemDto> selectCacheByInvoiceId(Long commonInvoiceId) {
        return CacheKit.cacheToRedis(
                () -> this.selectByInvoiceId(commonInvoiceId),
                INVOICE_ITEM_CACHE_BY_INVOICE_ID_FUNC.apply(commonInvoiceId),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }


    @Override
    public InvoiceItemDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                INVOICE_ITEM_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public InvoiceItemDto selectById(Long id) {
        InvoiceItemEntity entity = invoiceItemDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, InvoiceItemDto.class));
    }

    @Override
    public List<InvoiceItemDto> queryList(Map<String, Object> params) {
        List<InvoiceItemEntity> list = invoiceItemDao.queryList(params);
        List<InvoiceItemDto> result = CopyUtils.copyList(list, InvoiceItemDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private InvoiceItemDto paddingField(InvoiceItemDto dto) {
        if (dto != null) {

            if (InvoiceConstants.InvoiceItemSourceType.PROPERTY_BILL.getType().equals(dto.getSourceType())) {
                PropertyBillDto propertyBillDto = propertyBillService.selectCacheById(dto.getSourceId());
                dto.setPropertyBill(propertyBillDto);
            }
            if (InvoiceConstants.InvoiceItemSourceType.PARKING_BIll.getType().equals(dto.getSourceType())) {
                ParkingOrderDto parkingOrderDto = parkingOrderService.selectCacheById(dto.getSourceId());
                dto.setParkingOrderDto(parkingOrderDto);
            }
            if (InvoiceConstants.InvoiceItemSourceType.PARKING_CARD.getType().equals(dto.getSourceType())) {
                ParkingCardOrderDto parkingCardOrderDto = parkingCardOrderService.selectCacheById(dto.getSourceId());
                dto.setParkingCardOrderDto(parkingCardOrderDto);
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return invoiceItemDao.queryTotal(params);
    }

    @Override
    public Long save(InvoiceItemDto dto) {
        InvoiceItemEntity entity = CopyUtils.copyObj(dto, InvoiceItemEntity.class);
        entity.setId(Snowflake.nextId());
        invoiceItemDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(InvoiceItemDto dto) {
        InvoiceItemEntity entity = CopyUtils.copyObj(dto, InvoiceItemEntity.class);

        invoiceItemDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(InvoiceItemDto dto) {
        InvoiceItemEntity entity = CopyUtils.copyObj(dto, InvoiceItemEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, invoiceItemDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        invoiceItemDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
